import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/pages/Index'
import Home from '@/pages/Home'

Vue.use(VueRouter)

// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/login',
      name: '登录页',
      hidden: true,
      component: () => import('@/pages/Login'),
    },
    {
      path: '/',
      name: '首页',
      icon: 'el-icon-s-home',
      redirect: 'index',
      component: Layout,
      children: [
        {
          path: 'index',
          name: '首页',
          icon: 'el-icon-s-home',
          component: Home,
        }
      ]
    },
    {
      path: '/system',
      name: '系统管理',
      icon: 'el-icon-s-tools',
      component: Layout,
      children: [
        {
          path: 'user',
          name: '用户管理',
          component: () => import('@/pages/system/userList'),
        },
        {
          path: 'role',
          name: '角色管理',
          component: () => import('@/pages/system/roleList'),
        },
        {
          path: 'resource',
          name: '资源管理',
          component: () => import('@/pages/system/resourceList'),
        },
        {
          path: 'action',
          name: '动作管理',
          component: () => import('@/pages/system/actionList'),
        },
        {
          path: 'org',
          name: '组织管理',
          component: () => import('@/pages/system/orgList'),
        },
        {
          path: 'config',
          name: '参数配置',
          component: () => import('@/pages/system/configList'),
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {

  if (to.matched.length ===0) {  //如果未匹配到路由
    from.name ? next({ name:from.name }) : next('/');   //如果上级也未匹配到路由则跳转登录页面，如果上级能匹配到则转上级路由
  } else {
    next();    //如果匹配到正确跳转
  }

  if (to.path === '/login') {
    if (sessionStorage.getItem('zhanyun.token')) {
      next('/index')
    } else {
      next();
    }
  } else {
    if (!sessionStorage.getItem('zhanyun.token')) {
      next('/login');
    } else {
      next();
    }
  }
});

export default router;
